package jcode.project.rest.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RequestMapping(value = "/api/table")
@Controller
public class TableController {

    private Logger logger = LoggerFactory.getLogger(TableController.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping(value = "/query", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> query(String sql) {
        return jdbcTemplate.queryForList(sql);
    }

    @RequestMapping(value = "/count", method = RequestMethod.GET)
    @ResponseBody
    public Long count(String sql, HttpServletResponse response) {
        return jdbcTemplate.queryForObject(sql, Long.class);
    }

    @RequestMapping(value = "/insert/last_insert_id", method = RequestMethod.POST)
    @ResponseBody
    public Object insertAndLastInsertId(String sql) {

        jdbcTemplate.update(sql);

        Object id = jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", Object.class);
        logger.info("id=" + id);
        return id;

    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public void update(String sql) {
        jdbcTemplate.update(sql);
    }


}

